/**
 * 选择项目
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    var ui = require("ui");
    var angular = require("angular");
    require("angular-ui");
    var dialog = require("dialog");
    require("jqtree");

    var selectProjectSrv = angular.module('selectProjectSrv', ["ngUI"]);
    var api_prefix = G_CONFIG["api_prefix"] //api前缀
    var token = util.getToken();
    var $orgProjTree;
    var curApp;

    // 查询服务
    selectProjectSrv
        .factory('projService', ['$http', function projService($http) {
            var service = {
                data: [],
                // 选择项目
                selectProjDialog: function (app, dialog, dialogScope) {
                    var _this = this;
                    $orgProjTree = $('#proj_tree');

                    var $orgTree = $('#org_name_tree');

                    curApp = app;

                    var url = api_prefix + 'usermanage/organization/query-all-organizations';
                    this.data = angular.copy(app.list);

                    $http.get(url)
                        .success(function (data) {
                            if (data.retCode == 0) {
                                //左侧组织名称
                                $orgTree.tree("destroy");
                                $orgTree.tree({
                                    data: _this.fixedData(data.data),
                                    dragAndDrop: false,
                                    useContextMenu: false,
                                    autoOpen: 0, //展开级别
                                    onCreateLi: function (node, $li) {
                                        var id = node.id;
                                        $li.find(".jqtree-element").attr('id', node.id);
                                    }
                                }).on('tree.click', function (event) {
                                    var node = event.node;
                                    event.preventDefault();
                                    _this.getProjList(node.id, app.appcode);
                                    $orgTree.find('.jqtree-selected').removeClass('jqtree-selected');
                                    $("#" + node.id).closest('li').addClass('jqtree-selected');
                                });
                                setTimeout(function () {
                                    $orgTree.find(".jqtree-element").eq(0).trigger('click', event)
                                }, 200)
                            } else {
                                ui.showErrTip(data.errMsg);
                            }
                        })
                },
                confirm: function (data,callback) {
                    //绑定云Call客前，请检查并确认项目已经绑定移动销售及全民营销两个应用，是否继续绑定
                    var self = this;
                    if (data.appcode == '5030') {
                        util.confirm('绑定云Call客前，请检查并确认项目已经绑定移动销售及全民营销两个应用，是否继续绑定?',
                            {
                                ok: function(){
                                    curApp.list = self.data;
                                    callback?callback():'';
                                },
                                cancel: function () {
                                },
                                okValue:'继续绑定'
                            })
                    }else{
                        curApp.list = self.data;
                    }

                },
                // 判断是否有重复选中的项目
                unique: function (oldProject, id) {
                    for (var i = 0, len = oldProject.length; i < len; i++) {
                        if (id === oldProject[i].id) {
                            return false
                        }
                    }
                    return true
                },
                // 点击左侧组织名称显示对应列表
                getProjList: function (id, appcode) {
                    var _this = this;
                    var url = api_prefix + 'project/project/get-filter-project-list-by-organization-id';
                    var params = {
                        organizationId: id,
                        applicationCode: appcode,
                        token: token
                    };
                    $http.get(url, {params: params})
                        .success(function (data) {
                            if (data.retCode == 0) {
                                //右侧项目列表
                                $orgProjTree.tree('destroy');
                                $orgProjTree.tree({
                                    data: _this.fixedData(data.data),
                                    dragAndDrop: false,
                                    useContextMenu: false,
                                    autoOpen: 0, //展开级别
                                    onCreateLi: function (node, $li) {
                                        var id = node.p_projectId;
                                        var isFolder = "false";
                                        if (node.childNodes && node.childNodes.length > 0) {
                                            isFolder = "true"
                                        }
                                        var isChildrenAllSelected = _this.isChildrenAllSelected(node);
                                        var checked = util.inArray(node, _this.data, function (a, b) {
                                            return id === b.id;
                                        });
                                        if (checked || isChildrenAllSelected) {
                                            checked = 'checked';
                                        } else {
                                            checked = '';
                                        }
                                        $li.find(".jqtree-element").append("<label class='checkbox'><input " + checked + " type='checkbox' data-folder='" + isFolder + "' id='" + id + "' value='" + node.ProjName + "'><span>" + node.ProjName + "</span></label>");
                                        $li.find(".jqtree-title").remove();
                                    }
                                })
                                    .on('change', '.checkbox input', function (event) {
                                        event.preventDefault();

                                        $.proxy(_this.onSelectProj, this)();
                                    });
                            } else {
                                ui.showErrTip(data.errMsg);
                            }
                        })
                },
                isChildrenAllSelected: function (node) {
                    if (node.childNodes && node.childNodes.length > 0) {
                        var len = node.childNodes.length;
                        for (var i = 0; i < len; i++) {
                            var isChildrenChecked = util.inArray(node.childNodes[i], this.data, function (a, b) {
                                return a.p_projectId === b.id;
                            });
                            if (!isChildrenChecked) {
                                return false;
                            }
                        }
                        return true;
                    }
                    return false;
                },
                // 替换树节点属性名(childNodes 改成 children)
                fixedData: function (data) {
                    var _this = this;
                    angular.forEach(data, function (item) {
                        item.children = item.childNodes;
                        if (item.childNodes && item.childNodes.length > 0) {
                            _this.fixedData(item.childNodes);
                        }
                    });
                    return data;
                },
                // 绑定事件
                onSelectProj: function () {
                    var $this = $(this);

                    var proj = {id: $this.attr('id'), name: $this.val()};
                    var isFolder = $this.attr("data-folder");
                    var isChecked = $this.prop("checked");

                    if (isChecked && isFolder !== "true") {
                        service.data.push(proj);
                    } else {
                        util.removeFromArr(proj, service.data, function (a, b) {
                            return (a.p_projectId || a.id) === b.id;
                        });
                    }
                    if (isFolder === "true") {
                        $(this).closest('.jqtree-element').next().find("input").prop("checked", isChecked).trigger("change");
                    } else {
                        var ul = $(this).closest('ul');
                        var inputLen = ul.find("input").length;
                        var checkedLen = ul.find("input:checked").length;
                        if (inputLen === checkedLen) {
                            ul.prev().find("input").eq(0).prop("checked", true);
                        } else {
                            ul.prev().find("input").eq(0).prop("checked", false);
                        }
                    }
                }
            };
            return service;
        }]);
});